package com.aydqyy.springbootstart.interceptors;

import com.aydqyy.springbootstart.utils.JwtUtil;
import com.aydqyy.springbootstart.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //跨域访问时浏览器首先会发送Preflight请求，该请求不会携带Token，所以需要跳过该请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { // 跳过 OPTIONS 认证
           return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {  // ✅ 修正条件：Token 为空时拒绝
            response.setStatus(401);
            return false;
        }
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.setValue(claims);//设置线程本地变量
            return true;
        } catch (Exception e) {//http响应状态码为401response.setStatus(401);//不放行
            return false;
        }
      //return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
        ThreadLocalUtil.clear();//清空线程本地变量
    }

}
